package com.bitinstitute.parkapp.googlemaps;

import java.util.List;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;

import com.bitinstitute.parkapp.R;
import com.bitinstitute.parkapp.helper.AlertDialogManager;
import com.bitinstitute.parkapp.helper.GPSConnectionDetector;
import com.bitinstitute.parkapp.helper.InternetConnectionDetector;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.readystatesoftware.maps.OnSingleTapListener;
import com.readystatesoftware.maps.TapControlledMapView;

/**
 * 
 * This class will show the google API V1 - could be only used if you have a valid API 1 Key
 *
 */

public class TapControlledMap extends MapActivity {

	// Connection detector class
	InternetConnectionDetector cd;

	// flag for Internet connection status
	Boolean isInternetPresent = false;

	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	TapControlledMapView mapView; // use the custom TapControlledMapView
	List<Overlay> mapOverlays;
	Drawable penguin;
	Drawable fish;
	Drawable stork;
	SimpleItemizedOverlay itemizedOverlay;
	SimpleItemizedOverlay itemizedOverlay2;
	SimpleItemizedOverlay itemizedOverlay3;
	LocationManager locMgr;
	MyLocationListener locLstnr;
	private MapController mapController;
	GPSConnectionDetector gps;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_layout);

		cd = new InternetConnectionDetector(getApplicationContext());

		// Check if Internet present
		isInternetPresent = cd.isConnectingToInternet();
		if (!isInternetPresent) {
			// Internet Connection is not present
			alert.showAlertDialog(TapControlledMap.this,
					"Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			// return;
		}

		// creating GPS Class object
		gps = new GPSConnectionDetector(this);

		// Displaying Zooming controls
		mapView = (TapControlledMapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);

		// dismiss balloon upon single tap of MapView (iOS behavior)
		mapView.setOnSingleTapListener(new OnSingleTapListener() {
			public boolean onSingleTap(MotionEvent e) {
				itemizedOverlay.hideAllBalloons();
				return true;
			}
		});

		// setting up location listener
		locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locLstnr = new MyLocationListener();
		locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				locLstnr);

		mapOverlays = mapView.getOverlays();

		// first overlay
		penguin = getResources().getDrawable(R.drawable.map_penguin);
		itemizedOverlay = new SimpleItemizedOverlay(penguin, mapView);
		// set iOS behavior attributes for overlay
		itemizedOverlay.setShowClose(false);
		itemizedOverlay.setShowDisclosure(true);
		itemizedOverlay.setSnapToCenter(false);

		GeoPoint geoPenguin = new GeoPoint((int) (49.485134 * 1E6),
				(int) (8.457572 * 1E6));
		OverlayItem penguinOverlayItem = new OverlayItem(
				geoPenguin,
				"Humboldt-Pinguin",
				"Pinguine - damit verbindet man Eis und Schnee. Aber Pinguine am Rande der Atacamawüste?...");
		itemizedOverlay.addOverlay(penguinOverlayItem);

		mapOverlays.add(itemizedOverlay);

		// second overlay
		fish = getResources().getDrawable(R.drawable.map_fish);
		itemizedOverlay2 = new SimpleItemizedOverlay(fish, mapView);
		// set iOS behavior attributes for overlay
		itemizedOverlay2.setShowClose(false);
		itemizedOverlay2.setShowDisclosure(true);
		itemizedOverlay2.setSnapToCenter(false);

		GeoPoint geoFish = new GeoPoint((int) (49.484699 * 1E6),
				(int) (8.451826 * 1E6));
		OverlayItem fishOverlayItem = new OverlayItem(
				geoFish,
				"Anemonenfisch",
				"Anemonenfische leben in einer engen Lebensgemeinschaft mit Seeanemonen (Symbiose)...");
		itemizedOverlay2.addOverlay(fishOverlayItem);

		mapOverlays.add(itemizedOverlay2);

		// third overlay
		stork = getResources().getDrawable(R.drawable.map_stork);
		itemizedOverlay3 = new SimpleItemizedOverlay(stork, mapView);
		// set iOS behavior attributes for overlay
		itemizedOverlay3.setShowClose(false);
		itemizedOverlay3.setShowDisclosure(true);
		itemizedOverlay3.setSnapToCenter(false);

		GeoPoint geoStork = new GeoPoint((int) (49.486238 * 1E6),
				(int) (8.453624 * 1E6));
		OverlayItem storkOverlayItem = new OverlayItem(geoStork, "Weißstorch",
				"Warum klappert der Klapperstorch? Na, weil er nichts anderes kann!...");
		itemizedOverlay3.addOverlay(storkOverlayItem);

		mapOverlays.add(itemizedOverlay3);

		if (savedInstanceState == null) {

			// Bit Institute
			GeoPoint geoPointBIT = new GeoPoint((int) (49.484738 * 1E6),
					(int) (8.455233 * 1E6));

			mapController = mapView.getController();
			mapController.animateTo(geoPointBIT);
			mapController.setZoom(18);

		} else {

			// example restoring focused state of overlays
			int focused;
			focused = savedInstanceState.getInt("focused_1", -1);
			if (focused >= 0) {
				itemizedOverlay.setFocus(itemizedOverlay.getItem(focused));
			}
			focused = savedInstanceState.getInt("focused_2", -1);
			if (focused >= 0) {
				itemizedOverlay2.setFocus(itemizedOverlay2.getItem(focused));
			}
			focused = savedInstanceState.getInt("focused_3", -1);
			if (focused >= 0) {
				itemizedOverlay3.setFocus(itemizedOverlay3.getItem(focused));
			}

		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		// example saving focused state of overlays
		if (itemizedOverlay.getFocus() != null)
			outState.putInt("focused_1", itemizedOverlay.getLastFocusedIndex());
		if (itemizedOverlay2.getFocus() != null)
			outState.putInt("focused_2", itemizedOverlay2.getLastFocusedIndex());
		if (itemizedOverlay2.getFocus() != null)
			outState.putInt("focused_3", itemizedOverlay3.getLastFocusedIndex());
		super.onSaveInstanceState(outState);

	}

	public class MyLocationListener implements LocationListener {

		/**
		 * Called when the location changes. Will animate to the latest location
		 * 
		 * */
		public void onLocationChanged(Location loc) {

			String coordinates[] = { "" + loc.getLatitude(),
					"" + loc.getLongitude() };
			double lat = Double.parseDouble(coordinates[0]);
			double lng = Double.parseDouble(coordinates[1]);

			GeoPoint currentLocation = new GeoPoint((int) (lat * 1E6),
					(int) (lng * 1E6));

			mapController.animateTo(currentLocation);
			mapController.setZoom(15);

			// add a location marker.
			MyMapOverlays marker = new MyMapOverlays(currentLocation);
			List listOfOverLays = mapView.getOverlays();
			listOfOverLays.clear();
			listOfOverLays.add(marker);

			mapView.invalidate();

			mapView.invalidate();

			mapView.invalidate();

		}

		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Disabled",
					Toast.LENGTH_SHORT).show();
			// can't get location
			// GPS is not enabled
			// Ask user to enable GPS/network in settings
			gps.showSettingsAlert();
		}

		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Enabled",
					Toast.LENGTH_SHORT).show();
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

	}

	/* My overlay Class starts */
	class MyMapOverlays extends com.google.android.maps.Overlay {
		GeoPoint location = null;

		public MyMapOverlays(GeoPoint location) {
			super();
			this.location = location;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {

			super.draw(canvas, mapView, shadow);
			// translate the screen pixels
			Point screenPoint = new Point();
			mapView.getProjection().toPixels(this.location, screenPoint);

			// add the image
			canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
					R.drawable.map_me), screenPoint.x, screenPoint.y, null);
		}
	}

}
